#-*- coding:utf-8 -*-

from functools import wraps
from matplotlib import pyplot as plt
import cv2
import json
import math
import numpy as np
import os
import sys
import time
import util
reload(sys)
sys.setdefaultencoding("utf-8")

import glahf

def splice_image(img,startpoint,endpoint,
            datas=None):
    config = util.load_config()
    beginX = int(startpoint[0])
    beginY = int(startpoint[1])
    endX = int(endpoint[0])
    endY = int(endpoint[1])
    height,width = img.shape[:2]
    if datas is not None:
        H = int(datas['H'])
        V = int(datas['V'])
        offheight,offwidth = float(height)/V,float(width)/H
    else:
        offheight,offwidth = float(height)/config['vposcount'],float(width)/config['hposcount']
        
    CanvasH = int(endY*offheight)-int(beginY*offheight)
    CanvasW = int(endX*offwidth)-int(beginX*offwidth)
    spliced_img = np.zeros((CanvasH,CanvasW),np.uint8)
    spliced_img[:] = img[int(beginY*offheight):int(endY*offheight),
                                int(beginX*offwidth):int(endX*offwidth)]
    return spliced_img

def handle_images(f_face, l_face, r_face,
            f_ir_face, l_ir_face, r_ir_face, path='./'):
    config = util.load_config()
    if not(f_ir_face and l_ir_face and r_ir_face 
        and f_ir_face and l_ir_face and r_ir_face):
        raise AttributeError("路径不能为空")

    f_img = glahf.read(f_face)
    l_img = glahf.read(l_face)
    r_img = glahf.read(r_face)

    if f_img is None or l_img is None or r_img is None:
        raise glahf.ReadException("读取失败")

    h,w = f_img.shape[:2]
    l_img = cv2.resize(l_img,(w,h),interpolation=cv2.INTER_LINEAR)
    r_img = cv2.resize(r_img,(w,h),interpolation=cv2.INTER_LINEAR)
    vis = glahf.merge_image([l_img, f_img, r_img])
    vis = glahf.convert(vis)
    
    today = str(time.strftime("%Y-%m-%d", time.localtime()))
    date = str(time.strftime("%Y-%m-%d %H:%M %p", time.localtime()))

    tardir = os.path.join(path, today)
    if os.path.exists(tardir) is False:
        os.makedirs(tardir)

    time_ = str(int(time.time()))
    
    savepath = os.path.join(tardir, time_ +'.jpg')
    lines_savepath = os.path.join(tardir, time_ +'_lines.jpg')
    ir_savepath = os.path.join(tardir, time_ + '_ir.jpg')

    glahf.write(savepath, vis)
    glahf.write(lines_savepath, glahf.drawlines(vis, config['hposcount'], config['vposcount']))

    f_ir_img = glahf.read(f_ir_face)
    l_ir_img = glahf.read(l_ir_face)
    r_ir_img = glahf.read(r_ir_face)

    if f_ir_img is None or l_ir_img is None or r_ir_img is None:
        raise glahf.ReadException("读取失败")

    h, w = f_ir_img.shape[:2]
    l_ir_img = cv2.resize(l_ir_img, (w,h), interpolation=cv2.INTER_LINEAR)
    r_ir_img = cv2.resize(r_ir_img, (w,h), interpolation=cv2.INTER_LINEAR)
    ir_vis = glahf.merge_image([l_ir_img, f_ir_img, r_ir_img])
    ir_vis = glahf.convert(ir_vis)
    glahf.write(ir_savepath, ir_vis)

    arr = util.db_array()
    id = len(arr)
    datas = {}
    datas['H'] = config['hposcount']
    datas['V'] = config['vposcount']

    return {"id": str(id+1),
            "date": date,
            "path": savepath,
            "lines_path": lines_savepath,
            "ir_path": ir_savepath,
            "datas": datas
            }

def getavggrayvalue(vis, startpoint, endpoint
                ,datas=None):
    if vis is None:
        return
    if datas is not None:
        spliced_img = splice_image(vis, startpoint, endpoint, datas)
    else:
        spliced_img = splice_image(vis, startpoint, endpoint, None)
    return spliced_img,round(spliced_img.mean(),5)

def skin(face, mode='f', skinMask=None):
    h, w = face.shape[:2]
    if mode == 'l':
        face = face[0:h, w/4:w]
    elif mode == 'r':
        face = face[0:h, 0:w*3/4]
    elif mode !='f':
        # exception
        pass
    if skinMask is not None:
        skin, skinMask = glahf.pick_skin(face, skinMask)
        return skin
    else:
        skin, skinMask = glahf.pick_skin(face)
        return skin, skinMask

def showplt(img):
    '''
    show histogram of image.
    '''
    from matplotlib.font_manager import FontProperties
    font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)
    hist_full = cv2.calcHist([img],[0],None,[256],[0,256])
    plt.subplot(211),plt.imshow(img,'gray'),plt.title(u'结果', fontproperties=font)
    plt.subplot(212),plt.plot(hist_full,'gray'),plt.xlim([0,256])
    plt.xlabel(u'灰度范围', fontproperties=font)
    plt.ylabel(u'像素数量', fontproperties=font)
    plt.show()

def fn_timer(function):
    @wraps(function)
    def function_timer(*args, **kwargs):
        t0 = time.time()
        result = function(*args, **kwargs)
        t1 = time.time()
        print "Total time running <%s>: %s seconds" % (function.func_name, str(t1-t0))
        return result
    return function_timer